package com.weilele.mvvmlib.fragment

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.documentfile.provider.DocumentFile
import com.weilele.base.library.BaseBindingFragment
import com.weilele.base.library.FragmentContainerActivity
import com.weilele.mvvm.base.livedata.appCompatActivity
import com.weilele.mvvm.utils.result_contract.navigateForResult
import com.weilele.mvvmlib.databinding.FragmentSafBinding

class SafFragment : BaseBindingFragment<FragmentSafBinding>() {
    companion object{
        fun start(appCompatActivity: AppCompatActivity){
            FragmentContainerActivity.invoke<SafFragment>(appCompatActivity)
        }
    }
    override fun initUi(savedInstanceState: Bundle?) {
        super.initUi(savedInstanceState)
        navigateForResult<Activity>(
            intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
        ) { resultCode, intent ->
            val directoryUri = intent?.data ?: return@navigateForResult
            appCompatActivity?.contentResolver?.takePersistableUriPermission(
                directoryUri,
                Intent.FLAG_GRANT_READ_URI_PERMISSION
            )
            showDirectoryContents(directoryUri)
        }
    }

    private fun showDirectoryContents(directoryUri: Uri) {
        val documentsTree = DocumentFile.fromTreeUri(requireContext(), directoryUri) ?: return
        val childDocuments = documentsTree.listFiles()
    }
}